<?php
/**
 * Created by PhpStorm.
 * User: chentaohua
 * Date: 2019/8/13
 * Time: 14:46
 */

namespace App\Http\Libs;

use App\Models\UserModel;
use Illuminate\Support\Facades\Cache;

class StoreForget{

    /**
     * 获取验证码
     * @param string $phone 门店手机号码
     * @param int $code 验证码
     */
    public static function getCode($phone = '',$code){

        // 获取键
        $cacheName = self::cacheName($phone);

        $expireName = self::expireName($phone);

        // 验证在一分钟内是否有发送记录
        if(Cache::has($expireName)){
            throw new \Exception('一分钟内只能获取一次验证码');
        }

        // 设置缓存
        Cache::put($cacheName,$code,env('ALI_STORE_CACHE_PREFIX_TIME'));
        Cache::put($expireName,time(),env('ALI_STORE_CACHE_EXPIRE_KEY_TIME'));

        return true;

    }


    /**
     * 获取缓存键
     */
    private static function cacheName($phone){
        return env('ALI_STORE_CACHE_PREFIX') . $phone;
    }


    /**
     * 获取过期键
     */
    private static function expireName($phone){
        return env('ALI_STORE_CACHE_EXPIRE_KEY') . $phone;
    }


    /**
     * 验证验证码是否合法
     * @param string $phone 手机号码
     * @param string $code 验证码
     */
    public static function checkCode($phone,$code){

        // 验证是否已经获取验证码了
        $cacheName = self::cacheName($phone);
        if(!Cache::has($cacheName)){
           throw new \Exception('请先获取验证码');
           return false;
        }

        // 验证验证码是否合法
        if(Cache::get($cacheName) != $code){
            throw new \Exception('验证码不正确');
            return false;
        }

        if(Cache::get($cacheName) == $code){
            // 验证成功后 删除验证码
            Cache::forget($cacheName);
            return true;
        }

        return true;
    }

}